﻿using XiangziProjectTemplete.Core.Common.Helper;
using XiangziProjectTemplete.Core.Common.HttpContextUser;
using XiangziProjectTemplete.Core.Extensions.Others;
using XiangziProjectTemplete.Core.IServices;
using XiangziProjectTemplete.Core.Model;
using XiangziProjectTemplete.Core.Model.CommonModel;
using XiangziProjectTemplete.Core.Model.Models;
using XiangziProjectTemplete.Core.Model.ParamModels;
using XiangziProjectTemplete.Core.Utility;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using XiangziProjectTemplete.Core.Api.Common;

namespace XiangziProjectTemplete.Core.Api.Controllers
{
    /// <summary> 
    /// AGV报警 
    /// </summary> 
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize(Permissions.Name)]
    public class Les_AgvWarningController : ControllerBase
    {
        private readonly ILes_AgvWarningServices _Les_AgvWarningServices;
        private readonly IUserRoleServices _userRoleServices;
        private readonly IUser _user;
        private readonly ILogger<Les_AgvWarningController> _logger;

        public Les_AgvWarningController(IUserRoleServices userRoleServices, ILes_AgvWarningServices Les_AgvWarningServices, IUser user, ILogger<Les_AgvWarningController> logger)
        {
            _userRoleServices = userRoleServices;
            _Les_AgvWarningServices = Les_AgvWarningServices;
            _user = user;
            _logger = logger;
        }

        /// <summary> 
        /// 分页获取AGV报警列表 
        /// </summary> 
        /// <param name="param">筛选条件</param> 
        /// <returns>获取结果</returns> 
        [HttpPost]
        public async Task<MessageModel<PageModel<Les_AgvWarning>>> Get([FromBody] Les_AgvWarningParam param)
        {
            if (string.IsNullOrEmpty(param.searchVal) || string.IsNullOrWhiteSpace(param.searchVal))
            {
                param.searchVal = string.Empty;
            }

            var whereConditions = WhereConditionsExtensions.GetWhereConditions<Les_AgvWarning, Les_AgvWarningParam>(param);
            if (!whereConditions.IsSuccess)
            {
                return new MessageModel<PageModel<Les_AgvWarning>>()
                {
                    msg = whereConditions.ErrMsg,
                    success = false,
                    response = null
                };
            }
            var data = await _Les_AgvWarningServices.QueryPage(whereConditions.data, param.page, param.pageSize, " CreateTime desc ");
            return new MessageModel<PageModel<Les_AgvWarning>>()
            {
                msg = "获取成功",
                success = true,
                response = data
            };

        }

        /// <summary> 
        /// 获取单个AGV报警 
        /// </summary> 
        /// <param name="id">主键</param> 
        /// <returns>获取结果</returns> 
        [HttpGet]
        public async Task<MessageModel<Les_AgvWarning>> Get(int id = 0)
        {
            return new MessageModel<Les_AgvWarning>()
            {
                msg = "获取成功",
                success = true,
                response = await _Les_AgvWarningServices.QueryById(id)
            };
        }


        /// <summary> 
        /// 获取 最新的AGV报警 并且是 未读的 
        /// </summary> 
        /// <returns>获取结果</returns> 
        [HttpGet]
        [AllowAnonymous]
        public async Task<MessageModel<Les_AgvWarning>> GetLastOneAgvWarning()
        {
            #region 根据是否管理员进行过滤

            bool isManagerRole = await LesApiCommon.IsManagerRole(_userRoleServices, _user);
            if (isManagerRole == false)
            {
                return new MessageModel<Les_AgvWarning>()
                {
                    msg = "获取成功",
                    success = true,
                    response = null
                };
            }

            #endregion
            List<Les_AgvWarning> warnList = await _Les_AgvWarningServices.Query(x => x.IsKnow == 0 && x.Status == 0);
            if (warnList == null || warnList.Count == 0)
            {
                return new MessageModel<Les_AgvWarning>()
                {
                    msg = "获取成功",
                    success = true,
                    response = null
                };
            }
            var obj = warnList.OrderByDescending(x => x.CreateTime).ToList().First();
            return new MessageModel<Les_AgvWarning>()
            {
                msg = "获取成功",
                success = true,
                response = obj
            };
        }


        /// <summary> 
        /// 关闭AGV报警
        /// </summary> 
        /// <param name="request">要更新的AGV报警对象</param> 
        /// <returns>更新结果</returns> 
        [HttpPut]
        [AllowAnonymous]
        public async Task<MessageModel<string>> Put([FromBody] Les_AgvWarning request)
        {
            try
            {
                #region 验证 
                MessageModel<string> retBody = null;
                retBody = ValidateDataHelper.CommonValidateIsNULL<Les_AgvWarning, string>(request);
                if (retBody != null)
                {
                    return retBody;
                }

                List<ValidateModel> columnsList = null;
                columnsList = new List<ValidateModel>()
                {
                     new ValidateModel(){ ChinaName="主键",PropertyName="Id" },
                };
                retBody = ValidateDataHelper.CommonValidate<Les_AgvWarning, string>(request, columnsList);
                if (retBody != null)
                {
                    return retBody;
                }
                #endregion

                var dbObj = await _Les_AgvWarningServices.QueryById(request.Id);
                if (dbObj == null)
                {
                    return MessageModel<string>.Fail("数据不存在!");
                }

                dbObj.Status = Convert.ToInt32(AgvWarningStatusEnum.已处理);
                dbObj.StatusName = AgvWarningStatusEnum.已处理.ToString();
                dbObj.FinishTime = DateTime.Now;
                dbObj.CloseContent = request.CloseContent;

                var msg = "";
                DateTimeHelper.GetTimeDiffer(dbObj.WarningTime, dbObj.FinishTime, ref msg);
                dbObj.DurationTime = msg;

                dbObj.ModifyTime = DateTime.Now;
                dbObj.ModifyBy = _user.Name;
                dbObj.ModifyId = _user.ID;
                dbObj.OperationRemark = "更新";
                var success = await _Les_AgvWarningServices.Update(dbObj);

                if (success)
                {
                    return MessageModel<string>.Success("更新成功", request.Id.ObjToString());
                }
                return MessageModel<string>.Fail("更新失败");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新AGV报警出现异常:" + ex.Message);
                return MessageModel<string>.Fail("更新AGV报警出现异常:" + ex.Message);
            }
        }

        /// <summary>
        /// 更新全部报警为已处理
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<MessageModel<bool>> UpdateAllWarningDone([FromBody] Les_AgvWarning request)
        {
            try
            {
                var taskResult = await _Les_AgvWarningServices.UpdateAllWarningDone(_user.Name, request.CloseContent);
                if (!taskResult.IsSuccess)
                {
                    return new MessageModel<bool>()
                    {
                        msg = taskResult.ErrMsg,
                        success = false,
                        response = false
                    };
                }
                return new MessageModel<bool>()
                {
                    msg = "",
                    success = true,
                    response = true
                };
            }
            catch (System.Exception ex)
            {
                _logger.LogError("更新全部报警为已处理 异常", ex);
                return new MessageModel<bool>()
                {
                    msg = "异常:" + ex.Message,
                    success = false,
                    response = false
                };
            }
        }

        /// <summary>
        /// 报警信息知道了
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<MessageModel<bool>> UpdateWarningKnow([FromBody] Les_AgvWarning param)
        {
            try
            {

                #region 验证
                MessageModel<bool> retBody = null;
                retBody = ValidateDataHelper.CommonValidateIsNULL<Les_AgvWarning, bool>(param);
                if (retBody != null)
                {
                    return retBody;
                }
                List<ValidateModel> columnsList = null;
                columnsList = new List<ValidateModel>() {
                    new ValidateModel(){ ChinaName="警告ID", DataType=typeof(int), DataValue=param.Id },
                };

                retBody = ValidateDataHelper.CommonValidate<Les_AgvWarning, bool>(param, columnsList);
                if (retBody != null)
                {
                    return retBody;
                }
                //*/
                #endregion


                var taskResult = await _Les_AgvWarningServices.UpdateWarningKnow(param.Id, _user.Name);
                if (!taskResult.IsSuccess)
                {
                    return new MessageModel<bool>()
                    {
                        msg = taskResult.ErrMsg,
                        success = false,
                        response = false
                    };
                }
                return new MessageModel<bool>()
                {
                    msg = "",
                    success = true,
                    response = true
                };
            }
            catch (System.Exception ex)
            {
                _logger.LogError("报警信息知道了 异常", ex);
                return new MessageModel<bool>()
                {
                    msg = "异常:" + ex.Message,
                    success = false,
                    response = false
                };
            }
        }

        /// <summary> 
        /// 删除AGV报警 
        /// </summary> 
        /// <param name="id">主键</param> 
        /// <returns>删除结果</returns> 
        [HttpDelete]
        public async Task<MessageModel<string>> Delete(int id = 0)
        {
            try
            {
                var data = new MessageModel<string>();
                if (id > 0)
                {
                    var detail = await _Les_AgvWarningServices.QueryById(id);
                    if (detail != null)
                    {
                        data.success = await _Les_AgvWarningServices.DeleteById(detail.Id);
                        if (data.success)
                        {
                            data.msg = "删除成功";
                            data.response = detail?.Id.ObjToString();
                        }
                    }
                    else
                    {
                        return MessageModel<string>.Fail("数据不存在!");
                    }
                }
                else
                {
                    data.success = false;
                    data.msg = "删除失败,AGV报警不存在";
                }
                return data;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除AGV报警出现异常:" + ex.Message);
                return MessageModel<string>.Fail("删除AGV报警出现异常:" + ex.Message);
            }
        }

    }
}
